package com.fifth.apartment.service.impl;

import com.fifth.apartment.result.Result;
import com.fifth.apartment.service.KillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * TODO
 *
 * @author Dao
 * @since 2024/7/16
 */
@Service
public class KillServiceImpl implements KillService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Result killByLua(String pid, String uid) {
        Object obj = redisTemplate.execute((RedisCallback<Object>) connection -> {
            //1.加载Lua脚本
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
            redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("kill.lua")));
            //2.执行脚本  第一个参数：脚本的字节数组  第二个参数：Lua脚本执行后的返回值  第三个参数：键的数量
            String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
            Object result = connection.scriptingCommands().eval(
                    redisScript.getScriptAsString().getBytes(),
                    ReturnType.INTEGER,
                    2, pid.getBytes(), uid.getBytes(), date.getBytes());
            System.out.println("=========obj======"+result);
            return result;
        });

        //处理Lua脚本的返回值
        if(!ObjectUtils.isEmpty(obj)){
            Long result = Long.valueOf(obj.toString());
            if(result==1){
                return new Result(false , "活动未开始，秒杀失败！");
            }else if(result==2){
                return new Result(false , "活动已结束，秒杀失败！");
            }else if(result==3){
                return new Result(false , "当前用户已参与秒杀，秒杀失败！");
            }else if(result==4){
                return new Result(true , "恭喜秒杀成功！");
            }
        }
        return new Result(false , "秒杀失败~");
    }
}
